package com.example.fund.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import com.example.fund.Constant;
import com.example.fund.R;
import com.example.fund.amplitude.Amplitude;
import com.example.fund.amplitude.TimePeriod;
import com.example.fund.info.FundInfo;

public class FundUtil {
	private static final String fundBaseInfo = "http://fund.eastmoney.com/js/fundcode_search.js";
	
	private static List<Map<String, Object>> fundInfoList = new LinkedList<Map<String, Object>>();
	private static String lastFilterStr = null;
	private static List<String> lastOrderFieldList = new LinkedList<String>();
	private static FundInfo SHInfo = FundUtil.getFundNetValueFromLocalhost("上证", "0000001");
	public static final  String[] companyNames = new String[]{"华夏","易方达","工银","嘉实","南方","广发","建信","中银","汇添富","招商","博时","富国","华宝","鹏华","华安","银华","诺安","前海",
		"华泰","上投","兴全","国泰","农银","国投","交银","宝盈","中邮","景顺","中欧","民生","光大","华商","银河","申万","长盛","长信","信诚","泰达","浦银","新华","汇丰","金鹰","大摩","中海","海富通","天弘","国富","国联安"} ;
	 
/*	static
	{
		for(int i=0;i<Constant.indexNumbers.length;i++)
		{
			indexNumbers.add(Constant.indexNumbers[i][0]);
		}
	}*/
	
	/**
	 * 获取我关注的编号集合
	 * @param
	 * @return
	 */
	public static List<String> getMyFocusFund()
	{
		SQLiteDatabase db = DBManager.getDB();

		List<String> list = new ArrayList<String>();
		String sql = "select number from Fund where grade>0 order by grade desc,pinyin";
		Cursor c = db.rawQuery(sql.toString(), null);
		while (c.moveToNext())
		{
            String fundNumber = c.getString(c.getColumnIndex("number"));
            if(fundNumber!=null)
            {
            	list.add(fundNumber);
            }
		}
		c.close();
		
		return list;
	}
	
	/**
	 * 获取全部基金编号集合
	 * @param
	 * @return
	 */
	public static List<String> getAllFund()
	{
		SQLiteDatabase db = DBManager.getDB();

		List<String> list = new ArrayList<String>();
		String sql = "select number from Fund where (type like '%股票%' or type like '%混合%' or type like '%创新%' or type like '%指数%'  or type like '%分级%' or type like '%ETF%' or type like '%债券%' or type like '%QDII%' or type like '%联接%' or type like '%保本%') order by grade desc,pinyin";
		Cursor c = db.rawQuery(sql.toString(), null);
		while (c.moveToNext())
		{
            String fundNumber = c.getString(c.getColumnIndex("number"));
            if(fundNumber!=null)
            {
            	list.add(fundNumber);
            }
		}
		c.close();
		
		return list;
	}

	/**
	 * 获取全部基金名称
	 * @param
	 * @return
	 */
	public static List<String> getAllFundName(String company)
	{
		SQLiteDatabase db = DBManager.getDB();

		List<String> list = new ArrayList<String>();

		String sql = "select name from indexset where number!='0000000' order by seq ";
		Cursor c = db.rawQuery(sql.toString(), null);
		while (c.moveToNext())
		{
			String name = c.getString(c.getColumnIndex("name"));
			if(name!=null)
			{
				list.add(name);
			}
		}
		c.close();

		sql = "select name from Fund where (type like '%股票%' or type like '%混合%' or type like '%创新%' or type like '%指数%'  or type like '%分级%' or type like '%ETF%' or type like '%债券%' or type like '%QDII%' or type like '%联接%' or type like '%保本%') order by grade desc,pinyin";
		c = db.rawQuery(sql.toString(), null);
		while (c.moveToNext())
		{
			String name = c.getString(c.getColumnIndex("name"));
			if(!StringUtil.isNullOrEmpty(name))
			{
				if (!StringUtil.isNullOrEmpty(company))
				{
					if (name.contains(company))
					{
						list.add(name);
					}
				}else {
					list.add(name);
				}
			}
		}
		c.close();

		return list;
	}

	/**
	 * 根据名称获取编码
	 */
	public static String getFundNumber(String name)
	{
		SQLiteDatabase db = DBManager.getDB();

		String fundNumber = "";

		String sql = "select number from Fund where name = '"+name+"'";
		Cursor c = db.rawQuery(sql.toString(), null);
		if (c.moveToNext())
		{
			fundNumber = c.getString(c.getColumnIndex("number"));
		}
		c.close();

		if (StringUtil.isNullOrEmpty(fundNumber))
		{
			sql = "select number from indexset where name = '"+name+"' and number!='0000000'";
			c = db.rawQuery(sql.toString(), null);
			if (c.moveToNext())
			{
				fundNumber = c.getString(c.getColumnIndex("number"));
			}
			c.close();
		}

		return fundNumber;
	}
	
	/**
	 * 获取全部基金数量
	 * @param
	 * @return
	 */
	public static int getAllFundCount()
	{
		SQLiteDatabase db = DBManager.getDB();

		String sql = "select count(number) qty from Fund where (type like '%股票%' or type like '%混合%' or type like '%创新%' or type like '%指数%'  or type like '%分级%' or type like '%ETF%' or type like '%债券%' or type like '%QDII%' or type like '%联接%' or type like '%保本%')";
		Cursor c = db.rawQuery(sql.toString(), null);
		int qty = 0;
		if (c.moveToNext())
		{
            qty = c.getInt(c.getColumnIndex("qty"));
		}
		c.close();
		
		return qty;
	}
	
	/**
	 * 从本地加载基金的净值
	 * @param number
	 */
	public static FundInfo getFundNetValueFromLocalhost(String name,String number)
	{
		FundInfo fundInfo = new FundInfo();
		fundInfo.setNumber(number);
		fundInfo.setName(name);
		try {
			SQLiteDatabase db = DBManager.getDB();
			String sql = "select * from FundNetValue where fundNumber='"+number+"' and netValue>0 order by date desc";
			Cursor c = db.rawQuery(sql.toString(), null);
			while (c.moveToNext())
			{
	            String date = c.getString(c.getColumnIndex("date"));
	            double netValue = c.getDouble(c.getColumnIndex("netValue"));
	            double volume = c.getDouble(c.getColumnIndex("volume"));
	            fundInfo.getActualValues().put(date, String.valueOf(netValue));
	            
	       //     double volume = c.getDouble(c.getColumnIndex("volume"));
	            fundInfo.getVolumes().put(date, String.valueOf(volume));
			}
			c.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return fundInfo;
	}

	/**
	 * 从本地查询基金某一日期的净值
	 * @param number
	 */
	public static double getFundNetValue(String number,String date)
	{
		double netValue = 0;
		try {
			SQLiteDatabase db = DBManager.getDB();
			String sql = "select netValue from FundNetValue where fundNumber='"+number+"' and date='"+date+"' and netValue>0";
			Cursor c = db.rawQuery(sql.toString(), null);
			if (c.moveToNext())
			{
				netValue = c.getDouble(c.getColumnIndex("netValue"));
			}
			c.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return netValue;
	}
	
	/**
	 * 获取全部基金列表数据
	 * @param
	 * @return
	 */
	public static List<Map<String, Object>> getFundListOrderByAchievement(List<String> orderFieldList,String filterStr) 
	{
		SQLiteDatabase db = DBManager.getDB();

		boolean isChange = false;
		if((orderFieldList.size()!=lastOrderFieldList.size()) 
			|| (filterStr==null && lastFilterStr!=null) 
			|| (filterStr!=null && !filterStr.equals(lastFilterStr))
				)
		{
			isChange = true;
		}
		if(!isChange)
		{
			for(int i=0;i<orderFieldList.size();i++)
			{
				if(!orderFieldList.get(i).equals(lastOrderFieldList.get(i)))
				{
					isChange = true;
					break;
				}
			}
		}
		if(!isChange)
		{
			return fundInfoList;
		}
		lastOrderFieldList.clear();
		lastOrderFieldList.addAll(orderFieldList);
		lastFilterStr = filterStr;
		fundInfoList.clear();
		List<Map<String, Object>> fofList = FOFUtil.getFOFInfoList();
		fundInfoList.addAll(fofList);
		StringBuffer sqlQuery = new StringBuffer();
		if(orderFieldList.size()>0)
		{
			sqlQuery.append("	select			\n");
			sqlQuery.append("	fund.name,			\n");
			sqlQuery.append("	fund.number,			\n");
			sqlQuery.append("	fund.pinyin,			\n");
			sqlQuery.append("	fund.grade,			\n");
//			sqlQuery.append("	fund.type,			\n");
			sqlQuery.append("	case			\n");
			sqlQuery.append("	when fund.type like '%债券%' or fund.name like '%债%'	then 1		\n");
			sqlQuery.append("	else 2 end type,		\n");
			sqlQuery.append("	ifnull(1.0			\n");
			for(int i=0;i<orderFieldList.size();i++)
			{
				sqlQuery.append("	*(1.0+((fundNetValue1"+i+".netValue-fundNetValue2"+i+".netValue)/fundNetValue2"+i+".netValue))			\n");

			}
			
			sqlQuery.append("	,0) ratio1			\n");
			sqlQuery.append("	from fund fund			\n");
			for(int i=0;i<orderFieldList.size();i++)
			{
				String period = orderFieldList.get(i);
				if(period!=null && period.indexOf(":")>0)
				{
					String[] periodArr = period.split(":");
					sqlQuery.append("	left join fundNetValue fundNetValue1"+i+"			\n");
					sqlQuery.append("	on fund.number=fundNetValue1"+i+".fundNumber and fundNetValue1"+i+".date='"+periodArr[1]+"'			\n");
					sqlQuery.append("	left join fundNetValue fundNetValue2"+i+"			\n");
					sqlQuery.append("	on fund.number=fundNetValue2"+i+".fundNumber and fundNetValue2"+i+".date='"+periodArr[0]+"'			\n");
				}
			}
			
			sqlQuery.append("	where ratio1>0	\n");
			sqlQuery.append("	and type>1	\n");
			sqlQuery.append("	and (type like '%股票%' or type like '%混合%' or type like '%创新%' or type like '%指数%'	\n");
			sqlQuery.append("	       or type like '%分级%' or type like '%ETF%' or type like '%QDII%' or type like '%联接%' or type like '%保本%')	\n");
			if(filterStr!=null && filterStr.trim().length()>0)
			{
				sqlQuery.append("	and name like '%"+filterStr+"%'	\n");
			}
			sqlQuery.append("	order by ratio1 desc,pinyin			\n");
		}else
		{
			sqlQuery.append("	SELECT *	\n");
			sqlQuery.append("	FROM fund	\n");
			sqlQuery.append("	where (type like '%股票%' or type like '%混合%' or type like '%创新%' or type like '%指数%'	\n");
			sqlQuery.append("	       or type like '%分级%' or type like '%ETF%' or type like '%债券%' or type like '%QDII%' or type like '%联接%' or type like '%保本%')	\n");
			if(filterStr!=null && filterStr.trim().length()>0)
			{
				sqlQuery.append("	and name like '%"+filterStr+"%'	\n");
			}
			sqlQuery.append("	ORDER BY grade DESC,pinyin	\n");
		}
		
		Cursor c = db.rawQuery(sqlQuery.toString(), null);
		while (c.moveToNext())
		{
            String name = c.getString(c.getColumnIndex("name"));
            String number = c.getString(c.getColumnIndex("number"));
            String pinYin = c.getString(c.getColumnIndex("pinyin"));
            int grade = c.getInt(c.getColumnIndex("grade"));
            String type = c.getString(c.getColumnIndex("type"));
            
            Map<String, Object> map = new HashMap<String, Object>(); 
            map.put("number", number); 
            map.put("pinYin", pinYin); 
            map.put("name", name); 
            map.put("type", type); 
            if(grade==4)
            {
            	map.put("img", R.drawable.star4); 
            }else if(grade==3)
            {
            	map.put("img", R.drawable.star3); 
            }else if(grade==2)
            {
            	map.put("img", R.drawable.star2); 
            }else if(grade==1)
            {
            	map.put("img", R.drawable.star1); 
            }else
            {
            	map.put("img", R.drawable.star0);
            }
            fundInfoList.add(map); 
		}
		c.close();
		
        return fundInfoList; 
    }
	
	/**
	 * 关注、取消关注基金
	 * @param
	 * @param number
	 */
	public static void focusOrCancelFocusFund(String number)
	{
		SQLiteDatabase db = DBManager.getDB();

		String sqlQuery = "select grade from fund where number='"+number+"'";
		Cursor c = db.rawQuery(sqlQuery, null);
		if (c.moveToNext())
		{
			int grade = c.getInt(c.getColumnIndex("grade"));
			if(grade>=4)
			{
				grade = 0;
			}else
			{
				grade = 4;
			}
			
			String sqlUpdate = "update fund set grade="+grade+" where number='"+number+"'";
			db.execSQL(sqlUpdate);
		}
		c.close();
	}
	
	/**
	 * 获取最新的日期
	 * @param
	 * @param number
	 * @return
	 */
	public static String getFundLastDate(String number)
	{
		SQLiteDatabase db = DBManager.getDB();

		String lastDate = "";
		
		String sqlQuery = "select max(date) lastDate from FundNetValue where fundNumber='"+number+"'";
		Cursor c = db.rawQuery(sqlQuery, null);
		if (c.moveToNext())
		{
			String date = c.getString(c.getColumnIndex("lastDate"));
			if(date!=null)
			{
				lastDate = date;
			}
		}
		c.close();
		return lastDate;
	}
	
	
	/**
	 * 获取最新的日期
	 * @param
	 * @param
	 * @return
	 */
	public static Map<String,String> getFundLastDateMap()
	{
		SQLiteDatabase db = DBManager.getDB();

		Map<String,String> lastDateMap = new HashMap<String, String>();
		
		String sqlQuery = "select fundNumber,max(date) lastDate from FundNetValue group by fundNumber";
		Cursor c = db.rawQuery(sqlQuery, null);
		while (c.moveToNext())
		{
			String fundNumber = c.getString(c.getColumnIndex("fundNumber"));
			String date = c.getString(c.getColumnIndex("lastDate"));
			if(fundNumber!=null && date!=null)
			{
				lastDateMap.put(fundNumber, date);
			}
		}
		c.close();
		return lastDateMap;
	}
	
	/**
	 * 获取等级
	 * @param
	 * @param
	 * @return
	 */
	public static Map<String,String> getFundGradeMap()
	{
		SQLiteDatabase db = DBManager.getDB();

		Map<String,String> gradeMap = new HashMap<String, String>();
		
		String sqlQuery = "select number,grade from fund";
		Cursor c = db.rawQuery(sqlQuery, null);
		while (c.moveToNext())
		{
			String number = c.getString(c.getColumnIndex("number"));
			String grade = c.getString(c.getColumnIndex("grade"));
			gradeMap.put(number, grade);
		}
		c.close();
		return gradeMap;
	}
	
	/**
	 * 获取最早的日期
	 * @param
	 * @param number
	 * @return
	 */
	public static String getFundMinDate(String number)
	{
		SQLiteDatabase db = DBManager.getDB();

		String minDate = "";
		
		String sqlQuery = "select min(date) minDate from FundNetValue where fundNumber='"+number+"'";
		Cursor c = db.rawQuery(sqlQuery, null);
		if (c.moveToNext())
		{
			String date = c.getString(c.getColumnIndex("minDate"));
			if(date!=null)
			{
				minDate = date;
			}
		}
		c.close();
		
		String sqlQuery1 = "select defDate from indexset where number='"+number+"'";
		Cursor c1 = db.rawQuery(sqlQuery1, null);
		String defDate = null;
		if (c1.moveToNext())
		{
			String date = c1.getString(c1.getColumnIndex("defDate"));
			if(date!=null && date.trim().length()==10)
			{
				defDate = date;
			}
		}
		c1.close();
		
		if(defDate!=null && defDate.compareTo(minDate)>0)
		{
			minDate = defDate;
		}
		
		return minDate;
	}
	
	/**
	 * 更新基金基本信息
	 * @param
	 * @param
	 */
	public static void updateFundBaseInfo()
	{
//		String myFocus = AssetsUtil.getAssetsFile(activity, myfocusFileName);
		SQLiteDatabase db = DBManager.getDB();

		Map<String,String> goodFundMap = getGoodFundMap();
		Map<String,String> fundGraedMap = getFundGradeMap();
		
		HttpURLConnection con = null;
		BufferedReader reader = null;
		db.beginTransaction(); // 开始事务
		try
		{
			URL url = new URL(fundBaseInfo);
			con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("GET");
			reader = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
			String s = reader.readLine();
			if(s==null || s.trim().length()==0)
			{
				return;
			}
			s = s.substring(s.indexOf("["), s.lastIndexOf("]")+1);
			JSONArray jsonArrFund = new JSONArray(s);
        	for(int i=0;i<jsonArrFund.length();i++)
        	{
        		JSONArray fundArr = jsonArrFund.getJSONArray(i);
        		String number = fundArr.getString(0);
        		String pinYin = fundArr.getString(1);
        		String name = fundArr.getString(2);
        		String type = fundArr.getString(3);
        		if(number==null || number.trim().length()==0)
        		{
        			continue;
        		}
        		
        		boolean flag = false;
        		for(int j=0;j<companyNames.length;j++)
        		{
        			if(name.startsWith(companyNames[j]))
        			{
        				flag = true;
        				break;
        			}
        		}
        		if(!flag)
        		{
        			continue;
        		}
        		
        		String sqlAddOrUpdate = null;
        		if (fundGraedMap.keySet().contains(number))
        		{
        			 String grade = fundGraedMap.get(number);
        			 String grade1 = "0";
        			 if("4".equals(grade))
        			 {
        				 grade1 = "4";
        			 }else if(goodFundMap.keySet().contains(number))
        			 {
        				 grade1 = goodFundMap.get(number);
                         grade1 = "0";
        			 }
        			 sqlAddOrUpdate = "update fund set name='"+name+"',pinyin='"+pinYin+"',grade="+grade1+",type='"+type+"' where number='"+number+"'";
        		}else
        		{
        			String grade = "0";
        			sqlAddOrUpdate = "insert into fund(id,name,number,pinyin,grade,type) values (null,'"+name+"','"+number+"','"+pinYin+"',"+grade+",'"+type+"')";
        		}
        		db.execSQL(sqlAddOrUpdate);
        	}
			
			db.setTransactionSuccessful(); // 设置事务成功完成
		}catch (Exception e)
		{
			e.printStackTrace();
		}finally
		{
			db.endTransaction(); // 结束事务
			if(reader!=null)
			{
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(con!=null)
			{
				con.disconnect();
			}
		}
	}
	
	/**
	 * 获取上证指数的日期
	 */
	public static List<String> getSHIndexDateList() 
	{
		List<String> dateList = new LinkedList<String>();
		try {
			SQLiteDatabase db = DBManager.getDB();
			String sql = "select date from FundNetValue where fundNumber='0000001' order by date desc";
			Cursor c = db.rawQuery(sql.toString(), null);
			while (c.moveToNext())
			{
	            String date = c.getString(c.getColumnIndex("date"));
	            if(date!=null)
	            {
	            	dateList.add(date);
	            }
			}
			c.close();	
		} catch (Exception e) {
			e.printStackTrace();
		}

		return dateList;
	}
	
	/**
	 * 获取绩优基金
	 */
	public static Map<String,String> getGoodFundMap() 
	{
		SQLiteDatabase db = DBManager.getDB();
		Map<String,String> goodFundMap = new HashMap<String,String>();
		BigDecimal pRate = new BigDecimal("50.00");
		BigDecimal nRate = new BigDecimal("-40.00");
		List<String> dateList = getSHIndexDateList();
		List<String> amplitudeDateList = new TimePeriod(new Amplitude()).getSHAmplitudeDateList(dateList,pRate,nRate);
		if(amplitudeDateList==null || amplitudeDateList.size()<4)
		{
			return goodFundMap;
		}
		String date1 = amplitudeDateList.get(amplitudeDateList.size()-5);
		String date2 = amplitudeDateList.get(amplitudeDateList.size()-4);
		String date3 = amplitudeDateList.get(amplitudeDateList.size()-3);
		
		StringBuffer sqlQuery2 = new StringBuffer();
		sqlQuery2.append("	select			\n");
		sqlQuery2.append("	fund.name,			\n");
		sqlQuery2.append("	fund.number,			\n");
		sqlQuery2.append("	fund.pinyin,			\n");
		sqlQuery2.append("	fund.grade,			\n");
		sqlQuery2.append("	case			\n");
		sqlQuery2.append("	when fund.type like '%债券%' or fund.name like '%债%' or fund.type like '%指数%' or fund.name like '%二号%' or fund.name like '%贰号%'	then 1		\n");
		sqlQuery2.append("	else 2 end type1,		\n");
		sqlQuery2.append("	ifnull(1.0*(1.0+((fundNetValue1.netValue-fundNetValue2.netValue)/fundNetValue2.netValue)),0) ratio1			\n");
		sqlQuery2.append("	from fund fund			\n");
		sqlQuery2.append("	left join fundNetValue fundNetValue1			\n");
		sqlQuery2.append("	on fund.number=fundNetValue1.fundNumber and fundNetValue1.date=?			\n");
		sqlQuery2.append("	left join fundNetValue fundNetValue2			\n");
		sqlQuery2.append("	on fund.number=fundNetValue2.fundNumber and fundNetValue2.date=?			\n");
		sqlQuery2.append("	where ratio1>0	\n");
		sqlQuery2.append("	and type1>1	\n");
		sqlQuery2.append("	and (fund.type like '%股票%' or fund.type like '%混合%' or fund.type like '%创新%')	\n");
		sqlQuery2.append("	order by ratio1 desc,pinyin			\n");
		
		List<String> list0 = new LinkedList<String>();
		List<String> list1 = new LinkedList<String>();
		List<String> list2 = new LinkedList<String>();
		Set<String> set = new HashSet<String>();
		
		Cursor c = db.rawQuery(sqlQuery2.toString(), new String[]{date3,date1});
		Cursor c1 = db.rawQuery(sqlQuery2.toString(), new String[]{date3,date2});
		Cursor c2 = db.rawQuery(sqlQuery2.toString(), new String[]{date2,date1});
		boolean next0 = true;
		boolean next1 = true;
		while(set.size()<20 && c.moveToNext())
		{
			String number = c.getString(c.getColumnIndex("number"));
			if(number!=null)
			{
				list0.add(number);
				set.add(number);
			}
		}
		while(set.size()<85 && c1.moveToNext())
		{
			String number = c1.getString(c1.getColumnIndex("number"));
			if(number!=null)
			{
				list1.add(number);
				set.add(number);
			}
		}
		while(set.size()<150 && c2.moveToNext())
		{
			String number = c2.getString(c2.getColumnIndex("number"));
			if(number!=null)
			{
				list2.add(number);
				set.add(number);
			}
		}
			
		
		for(String number:set)
		{
			String grade = "0";
			boolean exist0 = list0.contains(number);
			boolean exist1 = list1.contains(number);
			boolean exist2 = list2.contains(number);
			if(exist0 || (exist1 && exist2))
			{
				grade = "3";
			}else if(exist1)
			{
				grade = "2";
			}else
			{
				grade = "1";
			}
			goodFundMap.put(number, grade);
		}
		c.close();
		c1.close();
		
		return goodFundMap;
	}
	
	/**
	 * 获取九转序列
	 * @param info
	 * @param dateList
	 * @return
	 */
	public static Map<String,String> getTDSeq(FundInfo info,List<String> dateList)
	{
		Map<String,String> TDSeqMap = new HashMap<String,String>();
		if(info==null || info.getActualValues().size()==0 
				|| dateList==null || dateList.size()==0)
		{
			return TDSeqMap;
		}
		
		int low9 = 0;
		int high9 = 0;
		for(int j=dateList.size()-1260;j>=0;j--)
		{
			String dateStr = dateList.get(j);
			String actValueStr = info.getActualValues().get(dateStr);
			if(actValueStr==null)
			{
				continue;
			}
			String dateStr1 = dateList.get(j+4);
			String actValueStr1 = info.getActualValues().get(dateStr1);
			if(actValueStr1==null)
			{
				continue;
			}
			double v = Double.valueOf(actValueStr);
			double v1 = Double.valueOf(actValueStr1);
			if(low9>0)
			{
				if(v<v1)
				{
					low9++;
				}else
				{
					low9=0;
				}
			}else
			{
				if(v<v1)
				{
					low9++;
				}
			}
			if(high9>0)
			{
				if(v>v1)
				{
					high9++;
				}else
				{
					high9=0;
				}
			}else
			{
				if(v>v1)
				{
					high9++;
				}
			}
			if(low9==9)
			{
				TDSeqMap.put(dateStr, "9");
				low9=0;
			}
			if(high9==9)
			{
				TDSeqMap.put(dateStr, "9");
				high9=0;
			}
			if(j==0)
			{
				if(low9>=6)
				{
					TDSeqMap.put(dateStr, low9+"");
				}
				if(high9>=6)
				{
					TDSeqMap.put(dateStr, high9+"");
				}
			}
		}
		return TDSeqMap;
	}

	public static FundInfo getAnnualFund(double annual,List<String> dateList)
	{
		FundInfo fund = new FundInfo();
		fund.setNumber("1111111");
		fund.setName("年化");

		double p = Math.pow((1.00d+(annual/100.00d)),1.0d/240.0d);
		String sDate = "1996-01-19";
		int startIndex = Math.max(dateList.indexOf(sDate),0);
		double lastValue = 0;
		int i = 0;
		for(int j=startIndex;j>=0;j--)
		{
			String dateStr = dateList.get(j);
			String actValueStr = SHInfo.getActualValues().get(dateStr);
			if(actValueStr!=null)
			{
				BigDecimal actValue = new BigDecimal(actValueStr);
				if(lastValue==0)
				{
					String beginValueStr = SHInfo.getActualValues().get(dateStr);
					lastValue = Double.valueOf(beginValueStr);
				}
				double v = lastValue*p;
				fund.getActualValues().put(dateStr,v+"");
				lastValue = v;
			}
		}

		return fund;
	}

	/**
	 * 清理垃圾数据
	 * @return
	 */
	public static boolean clearRubbishData()
	{
		try {
			SQLiteDatabase db = DBManager.getDB();
			StringBuffer sb = new StringBuffer();
			sb.append("	DELETE FROM fundnetvalue 			");
			sb.append("	WHERE fundNumber NOT IN ( 			");
			sb.append("	SELECT number FROM fund 			");
			sb.append("	UNION ALL 			");
			sb.append("	SELECT number FROM indexSet 			");
			sb.append("	)			");
			db.execSQL(sb.toString());
			
			sb.setLength(0);
			
			db.execSQL("delete from indexStocks where indexnumber not in(select number from indexset)");

	//	    String sql = "delete from indexStocks";
	//	    db.execSQL(sql.toString());

  //          db.execSQL("delete from fundTrade");

	//		db.execSQL("ALTER TABLE indexstocks ADD COLUMN startDate TEXT");
	//		db.execSQL("ALTER TABLE indexstocks ADD COLUMN endDate TEXT");

	//		db.execSQL("ALTER TABLE fundTrade ADD COLUMN account TEXT");
	//		db.execSQL("ALTER TABLE fundTrade ADD COLUMN tradePrice DOUBLE");
	//		db.execSQL("ALTER TABLE fundTrade ADD COLUMN tradeAmount DOUBLE");
	//		db.execSQL("ALTER TABLE fundTrade ADD COLUMN tradeRate DOUBLE");
	//		db.execSQL("ALTER TABLE fundTrade ADD COLUMN tradeQty DOUBLE");

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}



		Set<String> set = new HashSet<String>();
		set.add("2016-01-15@000831@1@10000");
		set.add("2016-01-28@000831@1@5000");
		set.add("2016-04-13@000831@2@5829.58");
		set.add("2016-05-30@100051@1@4000");
		set.add("2016-08-24@000831@2@5401.26");
		set.add("2016-08-24@630002@1@5000");
		set.add("2016-10-21@000831@2@5640.5");
		set.add("2016-10-21@630002@1@6000");
		set.add("2017-01-13@160224@1@10744.97");
		set.add("2017-02-14@100051@1@1000");
		set.add("2017-02-17@050024@1@2790.25");
		set.add("2017-02-17@502010@1@2790.25");
		set.add("2017-02-17@630002@2@6199.32");
		set.add("2017-02-20@164908@1@2832.32");
		set.add("2017-02-20@630002@2@3119.73");
		set.add("2017-04-26@160119@1@3000");
		set.add("2017-04-26@164908@2@3002.06");
		set.add("2017-07-10@502010@1@53.43");
		set.add("2017-08-21@502010@1@3124.17");
		set.add("2017-08-21@160224@2@3447.6");
		set.add("2017-08-24@502010@1@329.08");
		set.add("2017-08-28@001475@1@887.22");
		set.add("2017-08-28@001475@1@8149.19");
		set.add("2017-08-28@154945@1@2922.06");
		set.add("2017-08-28@160224@2@8993.6");
		set.add("2017-08-28@050024@2@3227.32");
		set.add("2017-10-30@001475@1@4125.2");
		set.add("2017-11-01@160119@2@3174");
		set.add("2017-11-03@154945@1@200");
		set.add("2017-11-06@502010@1@200");
		set.add("2017-11-10@154945@1@500");
		set.add("2017-11-17@001475@1@1500");
		set.add("2017-11-24@001475@1@148");
		set.add("2017-12-04@001475@1@1000");
		set.add("2017-12-04@502010@1@1000");
		set.add("2017-12-08@502010@1@1000");
		set.add("2017-12-15@100051@1@1000");
		set.add("2017-12-15@502010@1@1000");
		set.add("2017-12-18@100051@1@1000");
		set.add("2017-12-19@502010@1@1000");
		set.add("2017-12-22@502010@1@1000");
		set.add("2017-12-25@502010@1@1000");
		set.add("2017-12-25@001475@1@1000");
		set.add("2017-12-28@001475@1@1000");
		set.add("2018-01-09@100051@1@1000");
		set.add("2018-01-10@001475@1@1000");
		set.add("2018-01-12@001475@1@1000");
		set.add("2018-01-15@001475@1@1000");
		set.add("2018-01-16@001475@1@1000");
		set.add("2018-01-31@001475@1@1000");
		set.add("2018-02-01@001475@1@1210");
		set.add("2018-02-06@001475@1@1000");
		set.add("2018-02-07@001475@1@1000");
		set.add("2018-02-09@502010@1@1000");
		set.add("2018-03-21@001223@1@17504.4");

		for (String s:set)
		{
			String[] sArr = s.split("@");
			FundUtil1.saveTrade(sArr[1], sArr[0], Integer.valueOf(sArr[2]),Double.valueOf(sArr[3]));
		}

		return true;
	}
}
